import { proxy, subscribe, snapshot } from "valtio";
import { MessageSender, MessageRouter } from "@utils/messaging";
import { MessageType, type StorageChangedNotification, type GetDataRequest, type DataResponse, type SaveDataRequest, type BaseResponse } from "@utils/types";
import { STORAGE_KEYS } from "@utils/constants";

export interface AppStateShape {
  /** 用户token */
  token?: string;
  profile?: any;
}

export const appState = proxy<AppStateShape>({});

let isHydrating = false;
let lastPersistedHash = "";
export async function hydrateAppState() {
  isHydrating = true;
  try {
    const res = await MessageSender.sendToBackground<GetDataRequest, DataResponse>({ type: MessageType.GET_DATA, key: STORAGE_KEYS.USER_DATA });
    if (res?.success && res.data) {
      Object.assign(appState, res.data as any);
      lastPersistedHash = JSON.stringify(res.data);
    }
  } finally {
    isHydrating = false;
  }
}

let persistTimer: number | undefined;
subscribe(appState, () => {
  if (isHydrating) return;
  window.clearTimeout(persistTimer);
  persistTimer = window.setTimeout(() => {
    const data = snapshot(appState);
    const currentHash = JSON.stringify(data);
    if (currentHash === lastPersistedHash) return;
    lastPersistedHash = currentHash;
    MessageSender.sendToBackground<SaveDataRequest, BaseResponse>({
      type: MessageType.SAVE_DATA,
      key: STORAGE_KEYS.USER_DATA,
      data,
    });
  }, 400);
});

// 监听 background 广播的存储变更，并合并到 proxy
const router = new MessageRouter();
router.register(MessageType.STORAGE_CHANGED, async (message: StorageChangedNotification) => {
  const change = message.changes?.[STORAGE_KEYS.USER_DATA];
  if (change && change.newValue) {
    isHydrating = true;
    try {
      const payload = (change.newValue as any).value ?? change.newValue;
      Object.assign(appState, payload);
      lastPersistedHash = JSON.stringify(payload);
    } finally {
      isHydrating = false;
    }
  }
  return { success: true, timestamp: Date.now() } as any;
});
router.startListening();


